package com.yl.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class M3u8ToMp3Util {

    public static Boolean convertM3U8ToMP3(String m3u8FilePath, String outputMP3Path) {
        try {
            // 构建ffmpeg命令，这里假设ffmpeg在环境变量中
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "ffmpeg",
                    "-i", m3u8FilePath, // 输入的M3U8文件路径
                    "-vn", // 不处理视频
                    "-acodec", "mp3", // 指定输出音频编码为mp3
                    "-ar", "44100", // 设置音频采样率为44100Hz
                    "-ac", "2", // 设置音频通道数为2
                    "-b:a", "192k", // 设置音频比特率为192k
                    outputMP3Path // 输出的MP3文件路径
            );
            // 合并错误输出到标准输出
            processBuilder.redirectErrorStream(true);
            // 启动进程
            Process process = processBuilder.start();
            // 读取输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待进程结束
            int exitCode = process.waitFor();
            System.out.println("FFmpeg exited with error code : " + exitCode);
            return true;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        String m3u8FilePath = "https://zhishubucket-beijing.oss-cn-beijing.aliyuncs.com/leaderVideoFile/1813527497443127297/d4dfc77a3c4b3a970b8037b7986e3a1e_1813527497443127297__uid_s_504__uid_e_audio.m3u8"; // 替换为你的M3U8文件路径
        String outputMP3Path = "D:\\leaderVideoFile\\d4dfc77a3c4b3a970b8037b7986e3a1e_1813527497443127297__uid_s_504__uid_e_audio.mp3"; // 替换为你希望保存的MP3文件路径
        convertM3U8ToMP3(m3u8FilePath, outputMP3Path);
    }

}
